import asyncio
from dispatch import *

dispatch = Dispatch()

async def handle_echo(reader, writer):
    global dispatch
    data = await reader.read(1024)
    message = data.decode('utf-8')
    addr = writer.get_extra_info('peername')
    dispatch.run(message)
    print(f"Received {message} from {addr}")

    print(f"Sending data back to {addr}")
    writer.write(data)
    await writer.drain()
    print(f"Close the connection {addr}")
    writer.close()

async def main():
    server = await asyncio.start_server(handle_echo, '127.0.0.1', 8888)
    print('serving on {}'.format(server.sockets[0].getsockname()))
    await server.serve_forever()
    return 0

try:
    import uvloop
    uvloop.install()
    print('uvloop is enabled')
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    loop = uvloop.new_event_loop()
    asyncio.set_event_loop(loop)
except ImportError:
    print('uvloop is not available')

asyncio.run(main())


